class VideoMonitoring {
    constructor() {
        this.currentCamera = null;
        this.isRecording = false;
        this.isPaused = false;
        this.mediaRecorder = null;
        this.recordedChunks = [];
        this.videoSources = {
            'camera1': {
                id: 'camera1',
                name: 'A-1 水稻田东',
                url: '/videos/rice_east.mp4'
            },
            'camera2': {
                id: 'camera2',
                name: 'A-2 水稻田西',
                url: '/videos/rice_west.mp4'
            },
            'camera3': {
                id: 'camera3',
                name: 'B-1 小麦田北',
                url: '/videos/wheat_north.mp4'
            },
            'camera4': {
                id: 'camera4',
                name: 'B-2 小麦田中',
                url: '/videos/wheat_middle.mp4'
            },
            'camera5': {
                id: 'camera5',
                name: 'B-3 小麦田南',
                url: '/videos/wheat_south.mp4'
            },
            'camera6': {
                id: 'camera6',
                name: 'C-1 玉米地东',
                url: '/videos/corn_east.mp4'
            }
        };
        this.mediaStorage = {
            snapshots: [],
            recordings: []
        };
        this.initializeElements();
        this.setupEventListeners();
        this.loadInitialCamera();
        this.initializeTabs();
    }

    initializeElements() {
        // 视频元素
        this.videoElement = document.getElementById('mainVideo');
        // 控制按钮
        this.playPauseBtn = document.getElementById('playPause');
        this.snapshotBtn = document.getElementById('snapshot');
        this.recordBtn = document.getElementById('record');
        this.fullscreenBtn = document.getElementById('fullscreen');
        // 云台控制按钮
        this.ptzButtons = document.querySelectorAll('.ptz-btn');
        this.zoomButtons = document.querySelectorAll('.zoom-btn');
        // 搜索输入
        this.searchInput = document.getElementById('searchCamera');
    }

    setupEventListeners() {
        // 视频控制事件
        this.playPauseBtn.addEventListener('click', () => this.togglePlayPause());
        this.snapshotBtn.addEventListener('click', () => this.takeSnapshot());
        this.recordBtn.addEventListener('click', () => this.toggleRecording());
        this.fullscreenBtn.addEventListener('click', () => this.toggleFullscreen());

        // 云台控制事件
        this.ptzButtons.forEach(btn => {
            btn.addEventListener('mousedown', (e) => this.startPTZControl(e));
            btn.addEventListener('mouseup', () => this.stopPTZControl());
            btn.addEventListener('mouseleave', () => this.stopPTZControl());
        });

        // 变焦控制
        this.zoomButtons.forEach(btn => {
            btn.addEventListener('mousedown', (e) => this.startZoom(e));
            btn.addEventListener('mouseup', () => this.stopZoom());
            btn.addEventListener('mouseleave', () => this.stopZoom());
        });

        // 监控点切换
        document.querySelectorAll('.camera-item').forEach(item => {
            item.addEventListener('click', (e) => this.switchCamera(e));
        });

        // 预设位置
        document.querySelectorAll('.preset-btn').forEach(btn => {
            btn.addEventListener('click', (e) => this.moveToPreset(e));
        });

        // 搜索功能
        this.searchInput.addEventListener('input', (e) => this.searchCameras(e.target.value));

        // 分组展开/折叠
        document.querySelectorAll('.group-header').forEach(header => {
            header.addEventListener('click', (e) => this.toggleGroup(e));
        });
    }

    async loadInitialCamera() {
        try {
            // 使用视频文件模拟摄像头
            const videoUrl = '/videos/camera1_stream.mp4'; // 放在项目的videos目录下
            this.videoElement.src = videoUrl;
            // 或者使用远程视频流
            // this.videoElement.src = this.videoSources.camera1.url;
            
            this.currentCamera = {
                id: 'camera1',
                name: 'A-1 水稻田东',
                url: videoUrl
            };

            // 设置视频循环播放
            this.videoElement.loop = true;
            await this.videoElement.play();

        } catch (error) {
            console.error('加载视频流失败:', error);
            this.showErrorMessage('视频加载失败，请检查网络连接');
        }
    }

    togglePlayPause() {
        if (this.videoElement.paused) {
            this.videoElement.play();
            this.playPauseBtn.querySelector('i').className = 'fas fa-pause';
        } else {
            this.videoElement.pause();
            this.playPauseBtn.querySelector('i').className = 'fas fa-play';
        }
        this.isPaused = !this.isPaused;
    }

    async takeSnapshot() {
        const canvas = document.createElement('canvas');
        canvas.width = this.videoElement.videoWidth;
        canvas.height = this.videoElement.videoHeight;
        canvas.getContext('2d').drawImage(this.videoElement, 0, 0);
        
        try {
            const blob = await new Promise(resolve => canvas.toBlob(resolve, 'image/jpeg'));
            const url = URL.createObjectURL(blob);
            
            // 保存抓拍信息
            const snapshot = {
                id: Date.now(),
                url: url,
                name: this.currentCamera.name,
                time: new Date().toLocaleString(),
                type: 'snapshot',
                cameraId: this.currentCamera.id
            };
            
            this.mediaStorage.snapshots.push(snapshot);
            this.addToHistory('snapshot', snapshot);
            this.saveMediaToIndexedDB(snapshot);

            // 创建下载链接
            const a = document.createElement('a');
            a.href = url;
            a.download = `snapshot_${this.currentCamera.name}_${new Date().toISOString()}.jpg`;
            a.click();
        } catch (error) {
            console.error('截图失败:', error);
            this.showErrorMessage('截图失败');
        }
    }

    toggleRecording() {
        if (!this.isRecording) {
            this.startRecording();
        } else {
            this.stopRecording();
        }
    }

    startRecording() {
        this.recordedChunks = [];
        const stream = this.videoElement.captureStream();
        this.mediaRecorder = new MediaRecorder(stream, {
            mimeType: 'video/webm;codecs=vp9'
        });

        this.mediaRecorder.ondataavailable = (e) => {
            if (e.data.size > 0) {
                this.recordedChunks.push(e.data);
            }
        };

        this.mediaRecorder.onstop = async () => {
            const blob = new Blob(this.recordedChunks, { type: 'video/webm' });
            const url = URL.createObjectURL(blob);
            
            // 保存录像信息
            const recording = {
                id: Date.now(),
                url: url,
                name: this.currentCamera.name,
                time: new Date().toLocaleString(),
                type: 'recording',
                cameraId: this.currentCamera.id,
                duration: this.getRecordingDuration()
            };
            
            this.mediaStorage.recordings.push(recording);
            this.addToHistory('record', recording);
            this.saveMediaToIndexedDB(recording);

            // 自动下载录像
            const a = document.createElement('a');
            a.href = url;
            a.download = `recording_${this.currentCamera.name}_${new Date().toISOString()}.webm`;
            a.click();
        };

        this.recordingStartTime = Date.now();
        this.mediaRecorder.start();
        this.isRecording = true;
        this.recordBtn.querySelector('i').style.color = 'red';
        this.showMessage('开始录制');
    }

    getRecordingDuration() {
        return Math.round((Date.now() - this.recordingStartTime) / 1000);
    }

    // 使用 IndexedDB 存储媒体文件
    async initIndexedDB() {
        return new Promise((resolve, reject) => {
            const request = indexedDB.open('VideoMonitoring', 1);
            
            request.onerror = () => reject(request.error);
            request.onsuccess = () => {
                this.db = request.result;
                resolve();
            };
            
            request.onupgradeneeded = (e) => {
                const db = e.target.result;
                if (!db.objectStoreNames.contains('media')) {
                    db.createObjectStore('media', { keyPath: 'id' });
                }
            };
        });
    }

    async saveMediaToIndexedDB(media) {
        if (!this.db) {
            await this.initIndexedDB();
        }
        
        const transaction = this.db.transaction(['media'], 'readwrite');
        const store = transaction.objectStore('media');
        store.add(media);
    }

    async loadMediaHistory() {
        if (!this.db) {
            await this.initIndexedDB();
        }

        const transaction = this.db.transaction(['media'], 'readonly');
        const store = transaction.objectStore('media');
        const request = store.getAll();

        request.onsuccess = () => {
            const media = request.result;
            media.forEach(item => {
                if (item.type === 'snapshot') {
                    this.mediaStorage.snapshots.push(item);
                } else {
                    this.mediaStorage.recordings.push(item);
                }
                this.addToHistory(item.type, item);
            });
        };
    }

    stopRecording() {
        this.mediaRecorder.stop();
        this.isRecording = false;
        this.recordBtn.querySelector('i').style.color = '';
    }

    toggleFullscreen() {
        if (!document.fullscreenElement) {
            this.videoElement.requestFullscreen();
            this.fullscreenBtn.querySelector('i').className = 'fas fa-compress';
        } else {
            document.exitFullscreen();
            this.fullscreenBtn.querySelector('i').className = 'fas fa-expand';
        }
    }

    startPTZControl(event) {
        const direction = event.currentTarget.className.split(' ')[1];
        // 发送云台控制命令
        this.sendPTZCommand(direction, true);
    }

    stopPTZControl() {
        // 停止云台移动
        this.sendPTZCommand('stop', false);
    }

    sendPTZCommand(direction, start) {
        // 这里应该发送实际的云台控制命令到后端
        console.log(`PTZ ${direction} ${start ? 'started' : 'stopped'}`);
    }

    startZoom(event) {
        const direction = event.currentTarget.dataset.zoom;
        this.sendZoomCommand(direction, true);
    }

    stopZoom() {
        this.sendZoomCommand('stop', false);
    }

    sendZoomCommand(direction, start) {
        // 这里应该发送实际的变焦命令到后端
        console.log(`Zoom ${direction} ${start ? 'started' : 'stopped'}`);
    }

    async switchCamera(event) {
        const cameraItem = event.currentTarget;
        const cameraId = cameraItem.dataset.id;

        // 移除其他摄像头的激活状态
        document.querySelectorAll('.camera-item').forEach(item => {
            item.classList.remove('active');
        });
        cameraItem.classList.add('active');

        try {
            // 这里应该切换到实际的摄像头视频流
            await this.loadCameraStream(cameraId);
        } catch (error) {
            console.error('切换摄像头失败:', error);
        }
    }

    async loadCameraStream(cameraId) {
        try {
            const camera = this.videoSources[cameraId];
            if (!camera) {
                throw new Error('未找到摄像头');
            }

            // 如果正在录制，先停止录制
            if (this.isRecording) {
                this.stopRecording();
            }

            // 更新视频源
            this.videoElement.src = camera.url;
            this.currentCamera = camera;

            // 更新UI显示
            document.querySelector('.video-info h3').textContent = camera.name;
            
            await this.videoElement.play();

        } catch (error) {
            console.error('切换摄像头失败:', error);
            this.showErrorMessage('切换摄像头失败');
        }
    }

    moveToPreset(event) {
        const presetNumber = event.currentTarget.textContent.replace('位置', '');
        // 这里应该发送预设位置命令到后端
        console.log(`Moving to preset position ${presetNumber}`);
    }

    searchCameras(keyword) {
        const cameras = document.querySelectorAll('.camera-item');
        cameras.forEach(camera => {
            const name = camera.querySelector('.name').textContent.toLowerCase();
            if (name.includes(keyword.toLowerCase())) {
                camera.style.display = '';
            } else {
                camera.style.display = 'none';
            }
        });
    }

    toggleGroup(event) {
        const header = event.currentTarget;
        const group = header.parentElement;
        const items = group.querySelector('.camera-items');
        const icon = header.querySelector('i');

        if (items.style.display === 'none') {
            items.style.display = '';
            icon.className = 'fas fa-chevron-down';
        } else {
            items.style.display = 'none';
            icon.className = 'fas fa-chevron-right';
        }
    }

    addToHistory(type, media) {
        const historyList = document.querySelector('.history-list');
        const item = document.createElement('div');
        item.className = 'history-item';
        item.innerHTML = `
            <div class="history-info">
                <span class="history-type">${type === 'snapshot' ? '截图' : '录像'}</span>
                <span class="history-camera">${media.name}</span>
                <span class="history-time">${media.time}</span>
                ${type === 'recording' ? `<span class="history-duration">${media.duration}秒</span>` : ''}
            </div>
            <div class="history-actions">
                <button class="btn-view" onclick="window.open('${media.url}')">
                    <i class="fas fa-eye"></i>
                </button>
                <button class="btn-download" onclick="window.location.href='${media.url}'" download>
                    <i class="fas fa-download"></i>
                </button>
            </div>
        `;
        historyList.insertBefore(item, historyList.firstChild);
    }

    showErrorMessage(message) {
        // 创建错误提示元素
        const errorDiv = document.createElement('div');
        errorDiv.className = 'error-message';
        errorDiv.innerHTML = `
            <i class="fas fa-exclamation-circle"></i>
            <span>${message}</span>
        `;

        // 添加到视频播放器上方
        const videoPlayer = document.querySelector('.video-player');
        videoPlayer.appendChild(errorDiv);

        // 3秒后自动移除
        setTimeout(() => {
            errorDiv.remove();
        }, 3000);
    }

    showMessage(message) {
        // 创建消息提示元素
        const messageDiv = document.createElement('div');
        messageDiv.className = 'message-message';
        messageDiv.innerHTML = `
            <i class="fas fa-info-circle"></i>
            <span>${message}</span>
        `;

        // 添加到视频播放器上方
        const videoPlayer = document.querySelector('.video-player');
        videoPlayer.appendChild(messageDiv);

        // 3秒后自动移除
        setTimeout(() => {
            messageDiv.remove();
        }, 3000);
    }

    initializeTabs() {
        const tabButtons = document.querySelectorAll('.tab-btn');
        tabButtons.forEach(button => {
            button.addEventListener('click', () => {
                // 移除所有标签的激活状态
                tabButtons.forEach(btn => btn.classList.remove('active'));
                // 激活当前标签
                button.classList.add('active');

                // 隐藏所有内容
                const contents = document.querySelectorAll('.history-content');
                contents.forEach(content => content.classList.add('hidden'));

                // 显示对应内容
                const targetId = button.dataset.tab;
                document.getElementById(targetId).classList.remove('hidden');
            });
        });
    }
}

// 初始化视频监控
document.addEventListener('DOMContentLoaded', () => {
    new VideoMonitoring();
});

// 添加对应的CSS样式
const style = document.createElement('style');
style.textContent = `
    .error-message {
        position: absolute;
        top: 20px;
        left: 50%;
        transform: translateX(-50%);
        background: rgba(255, 0, 0, 0.8);
        color: white;
        padding: 10px 20px;
        border-radius: 4px;
        display: flex;
        align-items: center;
        gap: 8px;
        z-index: 1000;
    }
`;
document.head.appendChild(style); 